<template>
  <el-card>
    <el-form inline>
      <el-form-item>
        <el-input v-model="excUserName" placeholder="用户名" />
      </el-form-item>
      <el-button type="primary" @click="searchHandler">查询</el-button>
      <el-button type="default" @click="resetSearch">清空</el-button>
    </el-form>

    <div style="margin: 20px 0">
      <el-button type="primary" @click="additionHandler()">添 加</el-button>
      <el-button type="danger" @click="deleteAllUsers()">批量删除</el-button>
    </div>

    <el-table
      border
      stripe
      :data="paginationList"
      v-loading="loading"
      @selection-change="selectAllHandler"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="nickName" label="用户昵称" />
      <el-table-column prop="roleName" label="角色列表" width="200" />
      <el-table-column prop="gmtCreate" label="创建时间" width="180" />
      <el-table-column prop="gmtModified" label="更新时间" width="180" />

      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button
            type="info"
            icon="el-icon-user-solid"
            size="small"
            title="分配角色"
            @click="assigningRoles(row)"
          />
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit-outline"
            title="修改用户"
            @click="editUser(row)"
          />
          <el-popconfirm
            :title="`确定删除 ${row.username} 吗?`"
            @confirm="deleteUser(row)"
          >
            <template #reference>
              <el-button
                style="margin-left: 10px"
                type="danger"
                size="small"
                title="删除用户"
                icon="el-icon-delete"
              />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      :page-sizes="[5, 10, 20, 30]"
      style="padding: 20px 0"
      @current-change="getUsers"
      @size-change="handelChange"
      layout="prev, pager, next, jumper, ->, sizes, total"
    />

    <el-dialog
      :title="userInfo.id ? '修改用户' : '添加用户'"
      :visible.sync="userdialogUserVisible"
    >
      <el-form ref="userFormRef" label-width="120px">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="userInfo.username"  />
        </el-form-item>
        <el-form-item label="用户昵称" prop="">
          <el-input v-model="userInfo.nickName" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userInfo.id">
          <el-input v-model="userInfo.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="onsave">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="设置角色" :visible.sync="roledialogUserVisible">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="userRolesId"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="item in allRolesList"
              :key="item.id"
              :label="item.id"
              >{{ item.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="saveRoleHandler">保存</el-button>
        <el-button @click="roledialogUserVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
<script>
import userApi from "@/api/acl/user";
import { cloneDeep } from "lodash";
export default {
  name: "User",
  data() {
    return {
      page: 1,
      limit: 5,
      total: 0,
      excUserName: "",
      searchName: "",
      paginationList: [], //用来展示表格的数组
      loading: false, //用来控制label加载
      userdialogUserVisible: false, //用来控制添加跟修改时
      userInfo: {
        id: "",
        nickName: "",
        password: "",
        username: "",
      },
      userIds: [],
      roledialogUserVisible: false,
      allRolesList: [],
      assignRoles: [],
      userRolesId: [],
      checkAll: false,
      isIndeterminate: true,
    };
  },
  methods: {
    //获取分页数据展示列表数据
    async getPagination() {
      try {
        this.loading = true;
        let result = await userApi.getPageList(this.page, this.limit, {
          username: this.searchName,
        });
        (this.paginationList = result.data.items),
          (this.total = result.data.total);
        this.loading = false;
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    },
    //点击添加时把三个字段添加到userInfo
    async saveData() {
      try {
        const { nickName, password, username } = this.userInfo;
        let result = await userApi.add({ username, password, nickName });
        this.cancel();
        //重新获取页面
        this.getPagination();
      } catch (error) {
        console.log(error);
      }
    },
    //更新一个后台用户
    async updateAll(user) {
      try {
        let result = await userApi.update(user);
        this.cancel();
        this.getPagination();
      } catch (error) {
        console.log(error);
      }
    },
    //删除某个用户的功能函数
    async removeUser(id) {
      try {
        await userApi.removeById(id);
        this.getPagination();
      } catch (error) {
        console.log(error);
      }
    },
    //批量删除的回调
    async deleteAllUsers() {
      try {
        await this.userIds.forEach((item) => userApi.removeUsers(item));
        this.getPagination();
        this.$message({
          message: "批量删除数据成功",
          type: "success",
        });
      } catch (error) {
        console.log(error);
      }
    },
    //获取某个用户所拥有的角色功能函数
    async getAllRoles(userId) {
      try {
        let result = await userApi.getRoles(userId);
        this.allRolesList = result.data.allRolesList;
        this.assignRoles = result.data.assignRoles;
        this.userRolesId = result.data.assignRoles.map((item) => item.id);
        this.checkAll = this.allRolesList.length === this.assignRoles.length
        this.isIndeterminate = this.assignRoles.length>0 && this.assignRoles.length<this.allRolesList.length
      } catch (error) {
        console.log(error);
      }
    },
    //给用户分配角色的回调
    async getassignRoles() {
      try {
        let userId = this.userInfo.id;
        let roleId = this.userRolesId.join(",");
        let res = await userApi.assignRoles(userId, roleId);
        this.roledialogUserVisible = false;
        if(res.code === 20000){
          this.getPagination()
        }
      } catch (error) {
        console.log(error);
      }
    },
    //点击保存
    saveRoleHandler(){
      this.getassignRoles()
    },
    //点击分配角色
    assigningRoles(row) {
      this.getAllRoles(row.id);
      this.roledialogUserVisible = true;
      this.userInfo.username = row.username;
      this.userInfo.id = row.id
    },
    ///--------///
    handleCheckedCitiesChange(value) {
      this.checkAll = this.userRolesId.length === this.allRolesList.length && this.allRolesList.length > 0
      this.isIndeterminate = this.userRolesId.length > 0 && this.userRolesId.length < this.allRolesList.length
    },
    //全选
    handleCheckAllChange(val) {
      this.userRolesId = val ? this.allRolesList.map((item) => item.id) : [];
      this.isIndeterminate =
        this.userRolesId.length > 0 &&
        this.userRolesId.length < this.allRolesList.length;
    },
    //点击删除按钮删除一条数据
    deleteUser(row) {
      this.removeUser(row.id);
      this.$message({
        message: "删除数据成功",
        type: "success",
      });
    },
    //批量删除复选框的收集
    selectAllHandler(val) {
      console.log(val);
      this.userIds.push(val.map((item) => item.id));
    },
    //点击编辑出现编辑框
    editUser(row) {
      this.userdialogUserVisible = true;
      this.userInfo = cloneDeep(row);
    },
    //点击取消清空面板数据
    cancel() {
      this.userdialogUserVisible = false;
      (this.userInfo.nickName = ""),
        (this.userInfo.password = ""),
        (this.userInfo.username = ""),
        (this.userInfo.id = "");
    },
    //搜索
    searchHandler() {
      this.searchName = this.excUserName;
      this.getPagination();
    },
    //清楚搜索框数据
    resetSearch() {
      (this.excUserName = ""), (this.searchName = ""), this.getPagination();
    },
    //获取分页数据
    getUsers(val) {
      this.page = val;
      this.getPagination();
    },
    //获取分页数据
    handelChange(val) {
      this.limit = val;
      this.getPagination();
    },
    //点击添加弹出
    additionHandler() {
      this.userInfo = { }
      this.userdialogUserVisible = true;
    },
    //点击确定
    onsave() {
      if (this.userInfo.id) {
        this.updateAll(this.userInfo);
      } else {
        this.saveData();
      }
    },
  },
  mounted() {
    this.getPagination();
  },
};
</script>

<style scoped>
</style>